<template>
  <div class="chat-window" v-if="visible">
    <div class="chat-header">
      <div class="chat-user-info">
        <el-avatar 
          :size="40" 
          :src="getAvatarUrl(chatUser.avatar)" 
          @click="goToUserProfile"
          style="cursor: pointer;"
        />
        <span class="username">{{ chatUser.username }}</span>
      </div>
      <div class="chat-actions">
        <el-button type="text" @click="minimizeChat">
          <el-icon><Minus /></el-icon>
        </el-button>
        <el-button type="text" @click="closeChat">
          <el-icon><Close /></el-icon>
        </el-button>
      </div>
    </div>

    <div class="chat-messages" ref="messagesContainer">
      <div v-if="messages.length === 0" class="no-messages">
        <p>开始你们的对话吧！</p>
      </div>
      <div
        v-for="message in messages"
        :key="message.id"
        :class="['message', message.senderId === currentUserId ? 'sent' : 'received']"
      >
        <div class="message-avatar">
          <el-avatar 
            :size="32" 
            :src="getMessageAvatarUrl(message)" 
            :alt="getMessageSenderName(message)"
            @click="goToMessageSenderProfile(message)"
            style="cursor: pointer;"
          />
        </div>
        <div class="message-content">
          <div class="message-info">
            <span class="message-sender">{{ getMessageSenderName(message) }}</span>
            <span class="message-time">{{ formatTime(message.createTime) }}</span>
          </div>
          <div class="message-bubble">
            <p>{{ message.content }}</p>
          </div>
        </div>
      </div>
    </div>

    <div class="chat-input">
      <div v-if="!canSendMessage" class="send-restriction">
        <el-alert
          title="发送限制"
          :description="restrictionMessage"
          type="warning"
          :closable="false"
          show-icon
        />
      </div>
      <div class="input-area">
        <el-input
          v-model="newMessage"
          type="textarea"
          :rows="2"
          placeholder="输入消息..."
          :disabled="!canSendMessage"
          @keydown.enter.prevent="handleEnterKey"
          resize="none"
        />
        <el-button 
          type="primary" 
          @click="sendMessage"
          :disabled="!canSendMessage || !newMessage.trim()"
          :loading="sending"
        >
          发送
        </el-button>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, reactive, computed, watch, nextTick, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Close, Minus } from '@element-plus/icons-vue'
import axios from '@/utils/axiosConfig'

export default {
  name: 'ChatWindow',
  components: {
    Close,
    Minus
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    chatUser: {
      type: Object,
      required: true
    },
    currentUserId: {
      type: Number,
      required: true
    },
    currentUserAvatar: {
      type: String,
      default: ''
    }
  },
  emits: ['close', 'minimize'],
  setup(props, { emit }) {
    const router = useRouter()
    const messages = ref([])
    const newMessage = ref('')
    const sending = ref(false)
    const messagesContainer = ref(null)
    const canSendMessage = ref(true)
    const restrictionMessage = ref('')
    const messageCount = ref(0)
    const isFriend = ref(false)

    // 跳转到用户个人主页
    const goToUserProfile = () => {
      router.push(`/user/${props.chatUser.id}`)
    }

    // 获取消息发送者昵称
    const getMessageSenderName = (message) => {
      if (message.senderId === props.currentUserId) {
        return '我'
      } else {
        return message.senderUsername || props.chatUser.username || '未知用户'
      }
    }

    // 跳转到消息发送者的个人主页
    const goToMessageSenderProfile = (message) => {
      if (message.senderId === props.currentUserId) {
        // 如果是当前用户自己的消息，不跳转
        return
      }
      router.push(`/user/${message.senderId}`)
    }

    // 检查发送权限
    const checkSendPermission = async () => {
      try {
        const response = await axios.get(`/messages/check/${props.chatUser.id}`)
        if (response.data.success) {
          const data = response.data.data
          canSendMessage.value = data.canSend
          restrictionMessage.value = data.message || ''
          messageCount.value = data.messageCount || 0
          isFriend.value = data.areFriends || false
        } else {
          canSendMessage.value = false
          restrictionMessage.value = response.data.message || '无法检查发送权限'
        }
      } catch (error) {
        console.error('检查发送权限失败:', error)
        canSendMessage.value = false
        restrictionMessage.value = '无法检查发送权限'
      }
    }

    // 获取聊天记录
    const loadChatHistory = async () => {
      try {
        const response = await axios.get(`/messages/chat/${props.chatUser.id}`)
        if (response.data.success) {
          messages.value = response.data.data || []
        } else {
          messages.value = []
          ElMessage.error(response.data.message || '获取聊天记录失败')
        }
        await nextTick()
        scrollToBottom()
      } catch (error) {
        console.error('获取聊天记录失败:', error)
        ElMessage.error('获取聊天记录失败')
      }
    }

    // 发送消息
    const sendMessage = async () => {
      if (!newMessage.value.trim() || !canSendMessage.value) return

      sending.value = true
      try {
        const messageData = {
          receiverId: props.chatUser.id,
          content: newMessage.value.trim(),
          messageType: 0 // 文本消息
        }

        const response = await axios.post('/messages/send', messageData)
        
        if (response.data.success) {
          // 添加消息到本地列表
          const sentMessage = {
            id: Date.now(), // 临时ID
            senderId: props.currentUserId,
            receiverId: props.chatUser.id,
            content: newMessage.value.trim(),
            messageType: 0,
            createTime: new Date().toISOString(),
            status: 0
          }
          
          messages.value.push(sentMessage)
          newMessage.value = ''
          messageCount.value++
          
          // 重新检查发送权限
          await checkSendPermission()
          
          await nextTick()
          scrollToBottom()
          
          ElMessage.success('消息发送成功')
        } else {
          ElMessage.error(response.data.message || '发送失败')
        }
      } catch (error) {
        console.error('发送消息失败:', error)
        ElMessage.error('发送消息失败')
      } finally {
        sending.value = false
      }
    }

    // 处理回车键
    const handleEnterKey = (event) => {
      if (event.ctrlKey || event.shiftKey) {
        // Ctrl+Enter 或 Shift+Enter 换行
        return
      }
      // 普通 Enter 发送消息
      sendMessage()
    }

    // 滚动到底部
    const scrollToBottom = () => {
      if (messagesContainer.value) {
        messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
      }
    }

    // 格式化时间
    const formatTime = (timeString) => {
      const date = new Date(timeString)
      const now = new Date()
      const diff = now - date

      if (diff < 60000) { // 1分钟内
        return '刚刚'
      } else if (diff < 3600000) { // 1小时内
        return `${Math.floor(diff / 60000)}分钟前`
      } else if (diff < 86400000) { // 24小时内
        return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
      } else {
        return date.toLocaleDateString('zh-CN') + ' ' + date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
      }
    }

    // 获取头像URL
    const getAvatarUrl = (avatar) => {
      if (!avatar) return '/images/default-avatar.png'
      if (avatar.startsWith('http')) return avatar
      return `http://localhost:8081${avatar}`
    }

    // 获取消息头像URL
    const getMessageAvatarUrl = (message) => {
      if (message.senderId === props.currentUserId) {
        // 当前用户的头像
        return getAvatarUrl(props.currentUserAvatar)
      } else {
        // 对方用户的头像，优先使用消息中的头像信息
        const avatar = message.senderAvatar || props.chatUser.avatar
        return getAvatarUrl(avatar)
      }
    }

    // 关闭聊天窗口
    const closeChat = () => {
      emit('close')
    }

    // 最小化聊天窗口
    const minimizeChat = () => {
      emit('minimize')
    }

    // 监听聊天用户变化
    watch(() => props.chatUser, async (newUser) => {
      if (newUser && newUser.id) {
        await checkSendPermission()
        await loadChatHistory()
      }
    }, { immediate: true })

    // 监听窗口可见性变化
    watch(() => props.visible, (visible) => {
      if (visible) {
        nextTick(() => {
          scrollToBottom()
        })
      }
    })

    return {
      messages,
      newMessage,
      sending,
      messagesContainer,
      canSendMessage,
      restrictionMessage,
      messageCount,
      isFriend,
      sendMessage,
      handleEnterKey,
      formatTime,
      getAvatarUrl,
      getMessageAvatarUrl,
      getMessageSenderName,
      goToMessageSenderProfile,
      closeChat,
      minimizeChat,
      loadChatHistory,
      checkSendPermission,
      goToUserProfile
    }
  }
}
</script>

<style scoped>
.chat-window {
  width: 450px;
  height: 600px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12);
  display: flex;
  flex-direction: column;
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 1000;
  border: 1px solid #e4e7ed;
}

.chat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #e4e7ed;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px 12px 0 0;
  color: white;
}

.chat-user-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.username {
  font-weight: 600;
  color: white;
  font-size: 16px;
}

.chat-actions {
  display: flex;
  gap: 8px;
}

.chat-messages {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  background: #f8f9fa;
  min-height: 0;
}

.no-messages {
  text-align: center;
  color: #909399;
  margin-top: 80px;
  font-size: 14px;
}

.message {
  display: flex;
  margin-bottom: 16px;
  align-items: flex-end;
  animation: fadeInUp 0.3s ease-out;
  max-width: 100%;
}

.message.sent {
  flex-direction: row-reverse;
  justify-content: flex-start;
}

.message.received {
  justify-content: flex-start;
}

.message-avatar {
  margin: 0 8px;
  flex-shrink: 0;
  align-self: flex-end;
}

.message-avatar img {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  object-fit: cover;
  cursor: pointer;
  transition: all 0.2s ease;
  border: 2px solid transparent;
}

.message-avatar img:hover {
  transform: scale(1.05);
  border-color: #667eea;
  box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
}

.message-content {
  max-width: 75%;
  min-width: 60px;
  display: flex;
  flex-direction: column;
}

.message.sent .message-content {
  align-items: flex-end;
}

.message.received .message-content {
  align-items: flex-start;
}

.message-info {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 4px;
  font-size: 12px;
}

.message.sent .message-info {
  flex-direction: row-reverse;
}

.message-sender {
  font-weight: 500;
  color: #606266;
}

.message.sent .message-sender {
  color: #909399;
}

.message-time {
  font-size: 11px;
  color: #909399;
  opacity: 0.8;
}

.message-bubble {
  padding: 10px 14px;
  border-radius: 16px;
  word-wrap: break-word;
  line-height: 1.4;
  position: relative;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  margin-bottom: 4px;
}

.message.sent .message-bubble {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-bottom-right-radius: 4px;
}

.message.received .message-bubble {
  background: white;
  color: #303133;
  border: 1px solid #e4e7ed;
  border-bottom-left-radius: 4px;
}

.message-bubble p {
  margin: 0;
  font-size: 14px;
}

.chat-input {
  border-top: 1px solid #e4e7ed;
  background: white;
  border-radius: 0 0 12px 12px;
}

.send-restriction {
  padding: 12px 20px;
  background: #fff3cd;
  border-bottom: 1px solid #ffeaa7;
}

.input-area {
  padding: 16px 20px;
  display: flex;
  gap: 12px;
  align-items: flex-end;
  background: white;
}

.input-area .el-textarea {
  flex: 1;
}

.input-area .el-button {
  margin-bottom: 2px;
  border-radius: 20px;
  padding: 8px 20px;
}

/* 滚动条样式 */
.chat-messages::-webkit-scrollbar {
  width: 6px;
}

.chat-messages::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.chat-messages::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.chat-messages::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 动画效果 */
@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .chat-window {
    width: 90vw;
    height: 80vh;
    top: 10vh;
    left: 5vw;
    transform: none;
  }
}
</style>